<template>
  <div class="app-container home">
    <div class="left-container">
      <Tree
        :treeDataList="treeDataList"
        :dKey="dKey"
        :type="3"
        :treeLoading="treeLoading"
        @nodeClick="nodeClick"
        @getListTree="getListTree"
        @treeRrightClickEven="treeRrightClickEven"
      />
    </div>
    <div class="right-container">
      <div class="right-container-top right-container-bg">
        <div class="right-container-top-table">
          <div class="right-container-top-left-table">
            <div class="table-title" v-if="testParamList.length>0">测试参数</div>
            <el-table
              ref="multipleTable"
              border
              v-if="testParamList.length>0"
              :data="testParamList"
              style="width: 100%; margin-top: 10px"
              :header-cell-style="getTableHeaderStyle"
              :cell-style="getTableCellStyle"
            >
              <template v-if="tableTestParamColumn">
                <el-table-column v-for="(item,i) in Object.keys(tableTestParamColumn)" :key="i"
                                 :prop="item"
                                 :label="tableTestParamColumn[item]"
                                 header-align="center"
                >
                </el-table-column>
              </template>
              <template v-else>
                <el-table-column
                  prop=""
                  label=""
                  header-align="center"
                >
                </el-table-column>
              </template>

              <el-table-column width="60" label="操作" align="center">
                <template slot-scope="scope,row">
                  <el-link type="primary" icon="el-icon-search" :underline="false"
                           @click="selectTestParam(scope.row.rowguid)"></el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="right-container-top-right-table">
            <div class="table-title">数据来源</div>
            <el-table
              ref="multipleTable"
              border
              :data="dataFromList"
              style="width: 100%; margin-top: 10px"
              :header-cell-style="getTableHeaderStyle"
              :cell-style="getTableCellStyle"
            >
              <el-table-column
                prop="model_no"
                label="机器型号"
                header-align="center"
              >
              </el-table-column>
              <el-table-column
                prop="load_frequency"
                label="载荷频率"
                header-align="center"
              >
              </el-table-column>
              <el-table-column
                prop="data_provider"
                label="提供单位"
                header-align="center"
              >
              </el-table-column>
              <el-table-column width="60" label="操作" align="center">
                <template slot-scope="scope">
                  <el-link type="primary" icon="el-icon-search" :underline="false"
                           @click="selectDataSource(scope.row.rowguid)"></el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="right-container-top-option">
          <div class="option-buttons">
            <el-button
              type="danger"
              plain
              class="buttons buttons-del"
              icon="icon-del"
              @click="delData"
              :disabled="testParamList.length==0 && dataFromList.length==0"
            >删除数据
            </el-button
            >
            <el-button
              type="primary"
              plain
              class="buttons buttons-files"
              icon="icon-files"
              style="margin-left: 38px"
              @click="attachmentInfor"
              :disabled="paramData.dataFromId==null"
            >附件资料
            </el-button
            >
          </div>
        </div>
      </div>
      <div class="right-container-bottom right-container-bg">
        <div class="table-title">测试数据</div>
        <el-table
          ref="multipleTable"
          border
          :data="testDataList"
          style="width: 100%; margin-top: 10px"
          :height="heightTestData"
          :header-cell-style="getTableHeaderStyle"
          :cell-style="getTableCellStyle"
          v-loading="testDataListLoading"
        >
          <template v-if="testDataColList">
            <el-table-column v-for="(item,i) in Object.keys(testDataColList)" :key="i"
                             :prop="item"
                             :label="testDataColList[item]"
                             header-align="center"
            >
              <template slot="header" slot-scope="scope">
                <el-tooltip :content="testDataColList[item]" placement="top" effect="light">
                  <div style="width: 100%;white-space:nowrap;text-overflow:ellipsis;overflow: hidden;-o-text-overflow:ellipsis;">
                  {{testDataColList[item]}}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
          </template>
          <template v-else>
            <el-table-column
              prop=""
              label=""
              :show-overflow-tooltip="true"
              header-align="center"
            >
            </el-table-column>
          </template>
        </el-table>
      </div>
    </div>
    <el-dialog title="测试参数" :visible.sync="dialogTestParamListModel" width="800px">
      <el-table
        ref="multipleTable"
        border
        :data="dialogTestParamList"
        style="width: 100%; margin-top: 10px"
        :header-cell-style="getTableHeaderStyle"
        :cell-style="getTableCellStyle"
      >
        <template v-if="tableTestParamColumn">
          <el-table-column v-for="(item,i) in Object.keys(tableTestParamColumn)" :key="i"
                           :prop="item"
                           :label="tableTestParamColumn[item]"
                           header-align="center"
          >
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column prop="" label="" header-align="center">
          </el-table-column>
        </template>
        <el-table-column width="80" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini"
                       :disabled="scope.row.rowguid === dialogTestParamListActive"
                       @click="dialogTestParamListSelect(scope.row)"
            >
              选择
            </el-button>
            <!--            <el-checkbox :checked="scope.row.rowguid === dialogTestParamListActive" @change="tableTestParamCheck(scope.$index,$event)"></el-checkbox>-->
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
<!--    <el-button @click="dialogTestParamListModel = false">关 闭</el-button>-->
        <!--    <el-button type="primary" @click="dialogChangeTestParamList">选择</el-button>-->
  </span>
    </el-dialog>
    <el-dialog title="数据来源" :visible.sync="dialogDataSourceListModel" width="800px">
      <el-table
        ref="multiple-table"
        border
        :data="dialogDataSourceList"
        style="width: 100%; margin-top: 10px"
        :header-cell-style="getTableHeaderStyle"
        :cell-style="getTableCellStyle"
      >
        <el-table-column
          prop="model_no"
          label="机器型号"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          prop="load_frequency"
          label="载荷频率"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          prop="data_provider"
          label="提供单位"
          header-align="center"
        >
        </el-table-column>
        <el-table-column width="80" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" :disabled="scope.row.rowguid === dialogDataSourceListActive"
                       @click="dialogDataSourceListSelect(scope.row)">选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>
    <el-dialog title="附件资料" :visible.sync="dialogAttachmentListModel" width="800px">
      <dataF :param-data="paramData" ref="fileDialog"/>
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>
    <el-dialog title="导入性能分类" :visible.sync="dialogImportClassModel" width="500px">
      <el-upload
        action=""
        class="upload-demo"
        :limit="1"
        :before-upload="handleBeforeUpload"
        :on-remove="removeUpload"
        :file-list="fileList"
        :http-request="fileChange"
        v-model="dialogImportClassModelForm.file">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传excel文件，且不超过5M</div>
      </el-upload>
    </el-dialog>

    <div v-show="showTreeMenu" v-clickoutside="handler" :style="{ ...rightMenu }" class="treeMenu">
        <div v-if="treelevel ==1" @click="treetool()">
            <i class="el-icon-plus" style="color: #1e9fff"></i>
            导入数据
        </div>
        <div v-if="treelevel ==1" @click="downloadModel()">
            <i class="el-icon-download" style="color: #00aa00"></i>
            模板下载
        </div>
        <div v-if="treelevel ==2"  @click="treetool()">
            <i class="el-icon-edit" style="color: #fcc465"></i>
            导出数据
        </div>
    </div>
  </div>
</template>

<script>
  import service from "@/api/testData";
  import Tree from "../../common/tree.vue";
  import dataF from "./attachment.vue";
  import clickoutside from "element-ui/src/utils/clickoutside";
  import { getToken } from "@/utils/auth";

  export default {
    name: "Datafile",
    components: {
      Tree,dataF
    },
    props: {
      // 数量限制
      limit: {
        type: Number,
        default: 1,
      },
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 5,
      },
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
        type: Array,
        default: () => ["xlsx", "xls"],
      }
    },
    directives: { clickoutside },
    data() {
      return {
        treelevel:null,
        rightMenu:null,
        showTreeMenu: false,
        treeDataList: [],
        dKey: [],
        treeLoading: false,
        tableTestParamColumn: null,  // 测试参数表头字段
        testParamList: [], // 测试参数表头数据
        dataFromList: [], // 数据来源
        testDataColList: null, // 测试数据表头字段
        testDataList: [], // 测试数据列表

        // 测试参数列表请求ID
        testParamRequestID: {},
        testParamID: null,

        // 弹出层
        dialogTestParamListModel: false, // 测试参数列表 弹出层
        dialogTestParamList: [], // 测试参数数据列表
        dialogTestParamListActive: null, // 测试参数数据选中
        dialogDataSourceListModel: false, // 数据来源列表 弹出层
        dialogDataSourceList: [], // 测试参数数据列表
        dialogDataSourceListActive: null, // 测试参数数据选中

        dialogAttachmentListModel: false, // 测试参数数据选中

        dialogImportClassModel: false, // 导入
        dialogImportClassModelForm: {
          file: null,
          sel: null,
        }, // 导入
        paramData:{},
        fileList: [],
        treeSelectID: null, // tree 选中节点值

        baseUrl: process.env.VUE_APP_BASE_API,
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/business/materialtest/impFromExcelByMaterialType", // 上传文件服务器地址
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        heightTestData: 0,
        testDataListLoading: false,
      };
    },

    created() {
      // this.$store.dispatch('settings/changeSetting', {
      //   key: 'theme',
      //   value: '#409EFF'
      // })
      console.log('param')
      this.getListTree();
      // let param = {
      //   materialId: 'a213cf838dfc40679f597f2996879a07',
      //   materialTypeId: '86a719aef55211eea86200be437f964b',
      //   performanceId: 'bc08e5add93341b3a41280b3c68f6128'
      // }
      // this.testParamRequestID = param
      // this.getTestParamList(param)
    },
    mounted() {
      this.$nextTick(()=>{
        this.heightTestData = window.innerHeight - 350
      })
    },
    methods: {
      handler() {
        this.showTreeMenu = false
      },
      // 查询树形结构数据
      getListTree() {
        this.treeLoading = true;
        service.listTree().then((res) => {
            this.treeDataList = res.data;
            this.dKey = [res.data[0].children[0].id];
            let param = {
              materialId:res.data[0].id,
              materialTypeId: res.data[0].children[0].id,
              performanceId: res.data[0].children[0].children[0].id
            }
            this.testParamRequestID = param
          }).catch((e) => {
          }).finally(() => {
            this.treeLoading = false;
          });
      },
      // 点击树形节点
      nodeClick(params) {
        console.log(params)
        let param = {
          materialId: params.parent,
          materialTypeId: params.parents,
          performanceId: params.node.split('_')[1]
        }
        this.testParamRequestID = param
        this.paramData = param
        this.testDataListLoading = true
        this.getTestParamList(param)
      },
      // handleSelectionChange(val) {
      //   this.multipleSelection = val;
      // },
      // 设置表头样式
      getTableHeaderStyle() {
        return {
          background: "#EBF4FE",
          fontSize: "14px",
          fontWeight: "400",
          color: "#333333",
          padding: "3px 0",
          height: "30px"
        };
      },
      // 设置表格样式
      getTableCellStyle() {
        return {
          fontSize: "14px",
          textAlign: 'center',
          padding: "3px 0"
        };
      },
      // 获取测试数据参数数据
      getTestParamList(param) {
        this.testDataColList = null
        service.pageInitData(param).then((res) => {
          this.tableTestParamColumn =null
          this.testParamList =[]
          this.dataFromList =[]
          this.testDataList =[]

          this.tableTestParamColumn = res.data.paramColList[0]
          this.testParamList = res.data.testParamList
          this.dataFromList = res.data.dataFromList
          this.testDataList = this.fileSortData(res.data.testDataList)
          this.testDataColList = res.data.testDataColList[0]

          if(res.data.testParamList!=null && res.data.testParamList.length>0){
            this.paramData.paramId = res.data.testParamList[0].rowguid
          }
          this.paramData.dataFromId = res.data.dataFromList[0].rowguid
          }).catch((e) => {
          }).finally(() => {
          this.testDataListLoading = false
            this.treeLoading = false;
          });
      },
      // 列表排序
      fileSortData(jsonArray) {
        jsonArray.sort(function (a, b) {
          return a.age - b.age; // 升序排序，如果你想降序排序，可以改为 b.age - a.age
        });
        return jsonArray
      },
      // 选中数据参数数据
      selectTestParam(row) {
        // console.log(row)
        this.dialogTestParamListModel = true
        // let param = {
        //   materialId: '146734110f3046059ebb699f2779a28c',
        //   materialTypeId: '86a719aef55211eea86200be437f964b',
        //   performanceId: 'bc08e5add93341b3a41280b3c68f6128'
        // }
        // this.testParamRequestID
        service.getParamListByMaterialID(this.testParamRequestID).then((res) => {
          this.dialogTestParamList = res.data
          this.dialogTestParamListActive = row
        })
      },
      // 弹出层 选择功能
      dialogTestParamListSelect(row) {
        this.paramData.paramId = row.rowguid
        let param = {
          ...this.testParamRequestID,
          paramId: row.rowguid,
        }
        service.getDataByTestParam(param).then((res) => {
          console.log(res.data)
          this.testParamList = res.data.testParamList
          this.dataFromList = res.data.dataFromList
          this.testDataList = this.fileSortData(res.data.testDataList)
          this.dialogTestParamListModel = false
        }).catch((e) => {
        }).finally(() => {
        });
      },
      // 选中数据来源列表
      selectDataSource(row) {
        this.dialogDataSourceListModel = true
        let param = {
          ...this.testParamRequestID,
          paramId: this.paramData.paramId,
        }
        service.getDataFromListByParamID(param).then((res) => {
          console.log(res)
          this.dialogDataSourceList = res.data
          this.dialogDataSourceListActive = row
        })
      },
      // 选择数据来源列表弹出层数据
      dialogDataSourceListSelect(row) {
        console.log('row')
        console.log(Array(row))
        // let param = {
        //   materialId: '146734110f3046059ebb699f2779a28c',
        //   materialTypeId: '86a719aef55211eea86200be437f964b',
        //   performanceId: 'bc08e5add93341b3a41280b3c68f6128',
        //   paramId: 'bd5815fbd1b44dfa8d12636875984b10',
        // }
        this.paramData.dataFromId = row.rowguid
        this.dataFromList = Array(row)
        service.getDataByDataFrom(this.paramData).then((res) => {
          this.testDataList = this.fileSortData(res.data.testDataList)
          this.dialogDataSourceListModel = false
        }).finally(() => {
        })
      },
      // 删除数据
      delData() {
        this.$confirm('是否删除数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // let param = {
          //   materialId: '146734110f3046059ebb699f2779a28c',
          //   materialTypeId: '86a719aef55211eea86200be437f964b',
          //   performanceId: 'bc08e5add93341b3a41280b3c68f6128',
          //   paramId: 'bd5815fbd1b44dfa8d12636875984b10',
          // }
          let param = {
            ...this.testParamRequestID,
            paramId: this.paramData.paramId,
          }
          service.delDataByDataFrom(param).then(() => {
          }).catch((e) => {
          }).finally(() => {
            this.testDataListLoading = true
            this.getTestParamList(this.testParamRequestID)
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          });
        }).catch(() => {
        });
      },
      // 附件资料弹出层
      attachmentInfor(){
        this.dialogAttachmentListModel = true
        this.$refs.fileDialog.getList()
      },
      // 指标树 右键事件
      treeRrightClickEven(e,param){
        e.preventDefault() //关闭浏览器右键默认事件
        this.rightMenu = { top: e.pageY + 'px', left: e.pageX + 'px' }
        this.showTreeMenu = true
        if(param.node.level === 1){
          this.treelevel = 1
          this.treeparams = param
        }
        if(param.node.level === 2){
          this.treelevel = 2
          this.treeparams = param
        }
        if(param.node.level === 3){
          this.treelevel = 2
          this.treeparams = param
        }
      },
      //模板下载
      downloadModel(){
        this.$download.resource2("path")
      },
      // 指标树 右键事件  点击
      treetool(){
        console.log('this.testParamRequestID')
        console.log(this.testParamRequestID.materialId)
        if(this.treelevel === 1){
          this.dialogImportClassModel = true
          this.fileList = []
        }
        if(this.treelevel === 2){
          if(this.treeparams.node.level === 2){
            let params = {
              materialId: this.treeparams.id,
              materialTypeId: this.treeparams.node.parent.data.id,
              userId: this.$store.state.user.id
            }
            this.excelData(params)
          }
          if(this.treeparams.node.level === 3){
            let params = {
              materialId:  this.treeparams.node.parent.data.id,
              materialTypeId:  this.treeparams.node.parent.parent.data.id,
              performanceTypeId: this.treeparams.id.split('_')[1],
              userId: this.$store.state.user.id
            }
            this.excelData(params)
          }
        }
      },
      exportFile(param) {
        let url = service.expToExcelByMaterial(param)
        let a = document.createElement('a')
        a.setAttribute('href',url)
        a.setAttribute('target','_blank')
        a.style.display = 'none'
        let clickEvent = document.createEvent('MouseEvents')
        clickEvent.initEvent('click',true,true)
        a.dispatchEvent(clickEvent)
        document.body.removeChild(a)
      },
      excelData(param){
        this.$confirm('是否要导出数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.exportFile(param)
        }).catch(() => {
        });
      },
      dialogImportClassModelSave(){
        console.log(this.dialogImportClassModelForm)
      },
      removeUpload(file){
        console.log(file)
      },
      handleBeforeUpload(file){
        // 校检文件类型
        if (this.fileType) {
          const fileName = file.name.split('.');
          const fileExt = fileName[fileName.length - 1];
          const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
          if (!isTypeOk) {
            this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
            return false;
          }
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        // this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        this.headers['Content-Type'] = 'multipart/form-data'
        return true;
      },
      // 上传失败
      handleUploadError(err) {
        this.$modal.msgError("上传文件失败，请重试");
        this.$modal.closeLoading();
      },
      fileChange(data,type){
        var that = this
        console.log(type)
        let file = data.file
        let formData = new FormData()
        formData.append('file',file)
        formData.append('materialTypeId', that.treeparams.node.data.id)
        if(type){
          formData.append('flag', type)
        }
        console.log(data.file)
        that.fileList = [file]
        service.impFromExcelByMaterialTypem(formData).then(res => {
          console.log(res)
          if(res.data != "success"){
            that.$confirm('该材料对应的测试数据已经存在，请确认是否追加?', '提示', {
              confirmButtonText: '追加',
              cancelButtonText: '替换',
              type: 'warning'
            }).then(() => {
              that.fileChange(data,'0')
            }).catch(function (e) {
                if (e == 'cancel') {
                    // TODO 替换执行逻辑   B按钮逻辑
                    that.fileChange(data,'1')
                } else if(e == 'close') {
                    // TODO 右上角X的执行逻辑
                    that.dialogImportClassModel =false
                }
            });
          }else{
            that.$message({
              type: 'success',
              message: '上传成功!'
            });
            this.getListTree();
            that.dialogImportClassModel =false
          }
        }).catch((err)=>{
          if(err.code == 500){
            that.$modal.msgError(err.mas);
          }

        })
      }
    },
  };
</script>

<style scoped lang="scss">
  @import "@/assets/styles/container.scss";
  // 表格显示区域
  .right-container-top-table {
    width: 100%;
    float: left;
  }

  .right-container-top-left-table {
    width: 54%;
    float: left;
  }

  .right-container-top-right-table {
    width: 44%;
    margin-left: 2%;
    float: left;
  }

  .table-title {
    font-size: 14px;
    font-weight: 400;
    line-height: 21px;
    height: 26px;
    color: #5184ec;
    border-bottom: 1px solid #d5d5d5;
    background: url("../../../assets/images/line.png") no-repeat;
    background-position: -110px 22px;
  }

  // 表格下方按钮
  .right-container-top-option {
    width: 100%;
    padding-top: 13px;
    position: relative;
    float: left;
  }

  .option-buttons {
    float: right;
    margin-top: 5px;

    .option-input-text {
      float: left;
      font-size: 14px;
      line-height: 36px;
    }
  }

  // 按钮自定义
  .buttons {
    width: 140px;
    height: 35px;
    font-size: 15px;
    border-style: dashed;
  }

  .buttons-del {
    &:hover {
      color: #ff4949;
      background: #ffcfcf;
    }

    &:focus {
      color: #ff4949;
      background: #ffcfcf;
    }
  }

  .buttons-files {
    &:hover {
      color: #1890ff;
      background: #add8ff;
    }

    &:focus {
      color: #1890ff;
      background: #add8ff;
    }
  }

  ::v-deep .icon-del {
    width: 20px;
    height: 24px;
    background: url("../../../assets/images/del.png") center no-repeat;
    background-size: 90%;
    margin-right: 13px;
  }

  ::v-deep .icon-del:before {
    content: "图";
    visibility: hidden;
  }

  ::v-deep .icon-files {
    width: 20px;
    height: 24px;
    background: url("../../../assets/images/files.png") center no-repeat;
    background-size: 90%;
    margin-right: 13px;
  }

  ::v-deep .icon-files:before {
    content: "提";
    visibility: hidden;
  }

  .treeMenu {
      font-size: 14px;
      position: fixed;
      padding: 2px 0px 5px;
      z-index: 99999;
      top: 50%;
      left: 50%;
      background-color: rgba(255, 255, 255, 0.9);
      overflow: hidden;
      border-radius: 5px;
      border: 1px solid #e6ebf5;
      box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
      div {
          padding: 2px 10px;
          box-sizing: border-box;
          text-align: left;
      }
      div:hover {
          background-color: #eee;
          cursor: pointer;
      }
  }
  .app-container{
    padding: 5px;
  }
  .home .right-container{
    margin-left: 5px;
  }
  .home .right-container .right-container-bottom{
    margin-top: 5px;
    padding: 5px 20px 22px 20px;
  }
  .home .right-container .right-container-top{
    min-height: 150px;
    padding: 5px 20px  5px 20px;
  }
  ::v-deep .el-table__empty-text{
    line-height: 30px;
  }
  ::v-deep .el-table__empty-block{
    min-height: 30px;
  }
</style>
